package droid.frame.view;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * ViewPager工具类
 * 
 * @author wangt
 * 
 *         2013-10-28下午3:59:09
 */
public class ViewPagerExt extends android.support.v4.view.ViewPager {

	/**
	 * ViewPager管理的的页面
	 */
	private List<View> items = new ArrayList<View>();
	/**
	 * this
	 */
	private int scrollState = -1;
	/**
	 * 是否支持手势左右翻页。false为不支持。
	 */
	private boolean supportScroll = true;
	/**
	 * View 是否循环滚动
	 */
	private boolean isCircle;

	public ViewPagerExt(Context context) {
		super(context);
	}

	public ViewPagerExt(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	/**
	 * 设置是否支持左右划屏翻页
	 * 
	 * @param supportScroll
	 */
	public void setSupportScroll(boolean supportScroll) {
		this.supportScroll = supportScroll;
	}

	/**
	 * 以下两个方法。可以解决左右设置【翻页-左右不可滑动】
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (supportScroll) {
			return super.onTouchEvent(event);
		} else {
			return false;
		}
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent event) {
		if (supportScroll) {
			return super.onInterceptTouchEvent(event);
		} else {
			return false;
		}

	}

	// @Override
	// public void invalidateDrawable(Drawable paramDrawable) {
	// super.invalidateDrawable(paramDrawable);
	// invalidate();
	// }
	//
	// @Override
	// protected boolean verifyDrawable(Drawable paramDrawable) {
	// return true;
	// }
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// if (true) {
		// setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec));
		// View view = getChildAt(0);
		// if (view != null) {
		// // measure the first child view with the specified measure spec
		// view.measure(widthMeasureSpec, heightMeasureSpec);
		// int viewWidth = view.getMeasuredWidth();
		// int viewHeight = view.getMeasuredHeight();
		// // 宽度
		// if (viewWidth == 0) {
		// widthMeasureSpec = MeasureSpec.makeMeasureSpec(LayoutParams.WRAP_CONTENT, MeasureSpec.UNSPECIFIED);
		// } else {
		// widthMeasureSpec = MeasureSpec.makeMeasureSpec(viewWidth, MeasureSpec.EXACTLY);
		// }
		// // 高度
		// if (viewHeight == 0) {
		// heightMeasureSpec = MeasureSpec.makeMeasureSpec(LayoutParams.WRAP_CONTENT, MeasureSpec.UNSPECIFIED);
		// } else {
		// heightMeasureSpec = MeasureSpec.makeMeasureSpec(viewHeight, MeasureSpec.EXACTLY);
		// }
		// }
		// }
		int height = 0;
		for (int i = 0; i < getChildCount(); i++) {
			View child = getChildAt(i);
			child.measure(widthMeasureSpec, heightMeasureSpec);
			int h = child.getMeasuredHeight();
			if (h > height) {
				height = h;// 获取最大高度
			}
		}
		if (height > 0) {// 只有大于0的时候才设置
			heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
		}
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}

	/**
	 * Determines the height of this view
	 * 
	 * @param measureSpec
	 *            A measureSpec packed into an int
	 * @param view
	 *            the base view with already measured height
	 * 
	 * @return The height of the view, honoring constraints from measureSpec
	 */
	@SuppressWarnings("unused")
	private int measureHeight(int measureSpec, View view) {
		int result = 0;
		int specMode = MeasureSpec.getMode(measureSpec);
		int specSize = MeasureSpec.getSize(measureSpec);

		if (specMode == MeasureSpec.EXACTLY) {
			result = specSize;
		} else {
			// set the height from the base view if available
			if (view != null) {
				result = view.getMeasuredHeight();
			}
			if (specMode == MeasureSpec.AT_MOST) {
				result = Math.min(result, specSize);
			}
		}
		return result;
	}

	/**
	 * C 'ABC' A <br>
	 * 列表的首尾各增加一个元素 添加要显示页面到ViewPager <br>
	 * {@link #setFragmentItems(FragmentManager, Fragment...)}
	 */
	public void setViewItems(List<View> pages, boolean isCircle) {
		this.isCircle = isCircle;
		items.clear();
		items.addAll(pages);
		super.setAdapter(new PagerAdatperExt());
	}

	public void setFragmentItems(FragmentManager fm, Fragment... fragments) {
		ArrayList<Fragment> items = new ArrayList<Fragment>();
		items.addAll(Arrays.asList(fragments));
		setAdapter(new FragmentPagerAdapterExt(fm, items));
	}

	/**
	 * 获取page的数量<br>
	 * 如果page是循环展示的。则会去除头尾<br>
	 * 
	 * @return
	 */
	public int getPageCount() {
		int count = items.size();
		if (isCircle) {
			count = items.size() - 2;
		}
		if (count < 0) {
			count = 0;
		}
		return count;
	}

	public int getPageScrollState() {
		return this.scrollState;
	}

	public class ViewPageChangeListener extends android.support.v4.view.ViewPager.SimpleOnPageChangeListener {

		@Override
		public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
			// Log.i("on_PageScrolled", position + "");
		}

		@Override
		public void onPageScrollStateChanged(int state) {
			scrollState = state;
			if (isCircle && state == SCROLL_STATE_IDLE) {
				int curr = getCurrentItem();
				// 倒数第二个元素
				int lastReal = getAdapter().getCount() - 2;
				if (curr == 0) {
					setCurrentItem(lastReal, false);
				}
				// 如果-最后一个元素
				else if (curr == lastReal + 1) {
					setCurrentItem(1, false);
				}
			}
		}

		@Override
		public void onPageSelected(int position) {
			Log.i("on_PageSelected", position + "");

		}
	}

	/**
	 * ViewPager适配器(适合于普通的View)
	 * 
	 * @author wangtaoyfx <br>
	 *         2013-1-24上午9:33:55
	 */
	private class PagerAdatperExt extends PagerAdapter {

		@Override
		public int getCount() {
			return items.size();
		}

		/**
		 * 该方法必须被覆盖
		 */
		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			Log.i("on__destroyItem", position + "");
			removeView(items.get(position % items.size()));
		}

		/**
		 * 比较view与object是否为同一个对象，如果是则显示出胡来 如果不是则不显示 <br/>
		 * object即instantiateItem(ViewGroup,position)返回的对象
		 */
		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}

		/**
		 * java.lang.UnsupportedOperationException: Required method instantiateItem was not overridden
		 * 
		 * 显示当前ViewPager指定位置的视图 该方法必须被重载
		 * 
		 * @param container
		 * @param position
		 */
		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			Log.i("on__instantiateItem", position + "");
			int tmp = position % items.size();
			//
			// removeView(mItems.get(tmp));
			try {
				addView(items.get(tmp), 0);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return items.get(tmp);
		}
	}

	private class FragmentPagerAdapterExt extends FragmentPagerAdapter {
		private List<Fragment> fragmentsList;

		public FragmentPagerAdapterExt(FragmentManager fm) {
			super(fm);
		}

		public FragmentPagerAdapterExt(FragmentManager fm, List<Fragment> fragments) {
			super(fm);
			this.fragmentsList = fragments;
		}

		@Override
		public int getCount() {
			return fragmentsList.size();
		}

		@Override
		public Fragment getItem(int position) {
			return fragmentsList.get(position);
		}

		@Override
		public int getItemPosition(Object object) {
			return super.getItemPosition(object);
		}

	}

}
